
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:huajianshe_app/constants/constant.dart';
import 'package:huajianshe_app/utils/SpUtil.dart';


class HeaderInterceptor extends InterceptorsWrapper {
  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    options.connectTimeout = 1000 * 15;
    options.receiveTimeout = 1000 * 15;
    String token = SpUtil.getString(Constant.KEY_TOKEN);
    String accessToken = '49f796d839a929633970c215f74a47e2'; //todo 先写死
    options.headers['Access_Token'] = accessToken;
    print('token: $token');

    if (token.isNotEmpty) {
      // token = '306ca1b8723c2736d350fafe08e6a40e'; // todo 测试，写死
      options.headers[HttpHeaders.authorizationHeader] = token;
      options.headers['usersn'] = token;
    }
    super.onRequest(options, handler);
  }
}

class LoggingInterceptor extends Interceptor {
  DateTime? _startTime;
  DateTime? _endTime;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _startTime = DateTime.now();
    print('----------Start----------');
    if (options.queryParameters.isEmpty) {
      print('RequestUrl: ' + options.baseUrl + options.path);
    } else {
      print('RequestUrl: ' +
          options.baseUrl +
          options.path +
          '?' +
          Transformer.urlEncodeMap(options.queryParameters));
    }
    print('RequestMethod: ' + options.method);
    print('RequestHeaders:' + options.headers.toString());
    print('RequestContentType: ${options.contentType}');
    if (options.data is FormData) {
      FormData data = options.data as FormData;
      print('form data: ${data.fields.toString()}');
    } else {
      print('RequestData: ${options.data.toString()}');
    }

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _endTime = DateTime.now();
    final int duration = _endTime?.difference(_startTime ?? DateTime.now()).inMilliseconds ?? 0;
    if (response.statusCode == 200) {
      print('ResponseCode: ${response.statusCode}');
    } else {
      print('ResponseCode: ${response.statusCode}');
    }
    // 输出结果
    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
    log(encoder.convert(response.data)); //print 有字数限制
    print('----------End: $duration 毫秒----------');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print('----------Error-----------');
    super.onError(err, handler);
  }
}